<?php

namespace app\admin;

use app\BaseController;
use think\db\exception\DbException;
use think\Request;
use app\admin\common;
use Request\Request as RequestServerModel;
use app\admin\model\log\Log as LogModel;
use SnowFlake\Snowflake;
use think\facade\Session;

use app\common as appCommon;
/**
 * @title server 基类
 *
 */
class ServerBase extends BaseController
{
    public $writer_field = ['writer_name','writer_head_img','fans_num'];
    public $SUCCESS = "成功";
    public $ERROR = "失败";
    public $PINDEX = 10;
    public $PAGE = 1;
    public static $s_primary_key_model;
	public $_before_data_start;

    protected $validate;
    protected $model;
    protected $param;



    function getList()
    {
        [$page, $limit] = $this->getPage($this->param);
        [$list, $count] = $this->model->getList($this->request, [], '*', $page, $limit);
        $result['data'] = $list;
        $result['count'] = $count;
        $this->getMessageCode('adminMessage.success.select', 2);
        return $result;
    }

    function getDetail()
    {
        $info = $this->model->getFindById($this->request->param('id'));
        $this->getMessageCode('adminMessage.success.select', 2);
        return $info;
    }

    function add()
    {
        $post = $this->request->post();
        if (!$this->validate->scene('create')->check($post)) {
            $this->ERROR = $this->validate->getError();
            return false;
        }
        try {
            $this->model->save($post);
            $this->getMessageCode('adminMessage.success.insert', 2);
            return true;
        } catch (\Error $error) {
            $this->ERROR = $error->getMessage();
            return false;
        } catch (DbException $dbException) {
            $this->ERROR = $dbException->getMessage();
            return false;
        }
    }

    function edit()
    {
        $id = $this->request->param('id', 0);
        $post = $this->request->post();
        $post['id'] = $id;
        if (!$this->validate->scene('update')->check($post)) {
            $this->ERROR = $this->validate->getError();
            return false;
        }
        $info = $this->model->getFindById($id);
        if (empty($info)) {
            $this->getMessageCode('adminMessage.error.update', 1);
            return false;
        }
        if ($info->save($post)) {
            $this->getMessageCode('adminMessage.success.update', 2);
            return true;
        } else {
            $this->getMessageCode('adminMessage.error.update', 1);
            return false;
        }
    }

    function del()
    {
        $id = $this->request->param('id', 0);
        if (empty($id)) {
            $this->getMessageCode('adminMessage.error.delete', 1);
            return false;
        }
        $info = $this->model->whereIn('id',$id)->select();
        foreach ($info as $val){
            $val->delete();
        }
        $this->getMessageCode('adminMessage.success.delete', 2);
        return true;
    }



	public function sendMessage($_mobile,$_data,$_field){
    	$_app_common=new appCommon();
    	if($_app_common->replaceMessage($_mobile,$_data,$_field)==false){
    		$this->ERROR=$_app_common->ERROR;
    		$this->CODE=$_app_common->CODE;
    		return false;
    	}
    	return true;
    }
    public function beforeLog($operation_function, $model, $function, $where, $field, $name)
    {
        //1.查询
        $_common = new common();
        if (is_array($function)) {
            foreach ($function as $k => $v) {
            	
                if (!empty($where[$v])) {
                    $_before_data = $model->$v($where[$v], $field);
                } else {
                    $_before_data = $model->$v($where, $field);
                }
                if($k==0){
            		$this->_before_data_start=$_before_data;
            	}
                $_common->requestLog($operation_function, 'update', $_before_data, $name . "之前");
            }
        } else {
            $_before_data = $model->$function($where, $field);
            $_common->requestLog($operation_function, 'update', $_before_data, $name . "之前");
        }
        return $_before_data;
    }
    /**
     * @purpose 处理搜索 时的json数据
     */
 	public function checkParam(){
    	$_param=$this->REQUEST->param();
    	$_data=[];
    	foreach($_param as $k=>$v){
    		
    		if( $k == 'searchParams' )
    		{
    			$searchParams=json_decode($v,true);
    			if(!empty($searchParams ))
    			{
    				foreach($searchParams as $ka => $kv )
    				{
    					$_data[$ka]=$kv;
    				}	
    			}
    			continue;
    		}
    		$_data[$k]=$v;
    	}
    	return $_data;
    }
    function getLimit(){
        if(check_request($this->request,"limit")){
            return $this->request['limit'];
        }else{
            return 15;
        }
    }
    public function afterLog($operation_function, $model, $function, $where, $field, $name)
    {
        //1.查询
        $_common = new common();
        if (is_array($function)) {
            foreach ($function as $k => $v) {
                if (!empty($where[$v])) {
                    $_after_data = $model->$v($where[$v], $field);
                } else {
                    $_after_data = $model->$v($where, $field);
                }
                $_common->requestLog($operation_function, 'update', $_after_data, $name . "之后");
            }
        } else {
            $_after_data = $model->$function($where, $field);
            $_common->requestLog($operation_function, 'update', $_after_data, $name . "之后");
        }
        return $_after_data;
    }
	public function getAdmin(){
		global $_admin;
		return $_admin;
	}
    /**
     * 获取分页的数量
     *
     */
    public function getPageCount($_count)
    {
        $_pindex = $this->PINDEX;
       // $_count = ceil($_count / $_pindex);
        return $_count;
    }

    /**
     * 获取分页limit
     */
    public function getPage($data)
    {
        $limit = $data['limit']??15;
        $page = $data['page']??1;
        return [$page,$limit];
    }

    //记录所有CODE和msg
    public function getMessageCode($field, $flag)
    {
        if ($flag == 1) {
            $this->ERROR = config($field . '.msg');
        }
        $this->CODE = config($field . '.code');
        $this->SUCCESS = config($field . '.msg');
    }
    //自定义的返回msg和code
    public function setOtherMessageCode($msg, $flag,$code)
    {
        if ($flag == 1) {
            $this->ERROR = $msg;
        }
        $this->CODE =$code;
        $this->SUCCESS = $msg;
    }
    
     //获取操作人
	public function getOperationUser(){
		$operation=$this->getAdmin();
    	$data=[];
    	$data['update_time']=time();
    	$data['update_admin']=!empty($operation['username'])?$operation['username']:$operation['account'];
    	$data['or_data']=$operation;
    	return $data;
    }
    
    public function getUserId(){
    	$_session=Session::all();
    	return $_session['user_id'];
    }
    
    public function return_server($_data,$message_field){
    	if(!$_data){
			$this->getMessageCode('adminMessage.error.'.$message_field,1);
			return false;
		}
		$this->getMessageCode('adminMessage.success.'.$message_field,2);
		return true;
    }


}

?>